package com.terren.statistic.common.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 常用工具类
 * 
 * @author Administrator
 *
 */
public class CommonUtil {

	static Logger log = LogUtil.getLogger(CommonUtil.class);
	private static ClassPathXmlApplicationContext context;
	private static String[] springConfig = { "config/spring/applicationContext.xml" };

	/**
	 * 获取spring bean
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		if (null == context) {
			context = new ClassPathXmlApplicationContext(springConfig);
		}
		return context.getBean(name);
	}

	/**
	 * 获取spring bean
	 * 
	 * @param requiredType
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredType) {
		if (null == context) {
			context = new ClassPathXmlApplicationContext(springConfig);
		}
		return context.getBean(requiredType);
	}

	public static <T> String getProjectPath(Class<T> cls) {
		String filePath = null;
		try {
			URL url = cls.getProtectionDomain().getCodeSource().getLocation();
			filePath = URLDecoder.decode(url.getPath(), "utf-8");
			if (filePath.endsWith(".jar")) {
				filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
			}
			File file = new File(filePath);
			filePath = file.getAbsolutePath();
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		return filePath;
	}

	public static <T> String getRealPath(Class<T> cls) {
		String realPath = cls.getClassLoader().getResource("").getFile();
		File file = new File(realPath);
		realPath = file.getAbsolutePath();
		try {
			realPath = URLDecoder.decode(realPath, "utf-8");
		} catch (Exception e) {
			log.error(realPath + " not found:", e);
		}
		return realPath;
	}

	public static <T> String getRealPath(Class<T> cls, String filename) {
		String realPath = cls.getClassLoader().getResource(filename).getFile();
		File file = new File(realPath);
		realPath = file.getAbsolutePath();
		try {
			realPath = URLDecoder.decode(realPath, "utf-8");
		} catch (Exception e) {
			log.error(realPath + " not found:", e);
		}
		return realPath;
	}

	/**
	 * 获得随机数
	 * 
	 * @param minInt
	 * @param maxInt
	 * @return
	 */
	public static int getRandomInt(int minInt, int maxInt) {
		int number = maxInt - minInt + 1;

		Random random = new Random();

		int ranNum = random.nextInt(number) + minInt;// 0-5

		return ranNum;
	}

	/**
	 * 判断字符串中是否包含中文
	 * 
	 * @param str 待校验字符串
	 * @return 是否为中文
	 * @warn 不能校验是否为中文标点符号
	 */
	public static boolean isContainChinese(String str) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	/**
	 * 使用正则表达式来判断字符串中是否包含字母
	 * 
	 * @param str 待检验的字符串
	 * @return 返回是否包含 true: 包含字母 ;false 不包含字母
	 */
	public static boolean isContainsEnglish(String str) {
		String regex = ".*[a-zA-Z]+.*";
		Matcher m = Pattern.compile(regex).matcher(str);
		return m.matches();
	}

	/**
	 * 过滤掉中文
	 * 
	 * @param str 待过滤中文的字符串
	 * @return 过滤掉中文后字符串
	 */
	public static String filterChinese(String str) {
		// 用于返回结果
		String result = str;
		boolean flag = isContainChinese(str);
		if (flag) {// 包含中文
			// 用于拼接过滤中文后的字符
			StringBuffer sb = new StringBuffer();
			// 用于校验是否为中文
			boolean flag2 = false;
			// 用于临时存储单字符
			char chinese = 0;
			// 5.去除掉文件名中的中文
			// 将字符串转换成char[]
			char[] charArray = str.toCharArray();
			// 过滤到中文及中文字符
			for (int i = 0; i < charArray.length; i++) {
				chinese = charArray[i];
				flag2 = isChinese(chinese);
				if (!flag2) {// 不是中日韩文字及标点符号
					sb.append(chinese);
				}
			}
			result = sb.toString().trim();
		}
		return result;
	}

	/**
	 * 校验一个字符是否是汉字
	 *
	 * @param c 被校验的字符
	 * @return true代表是汉字
	 */
	public static boolean isChineseChar(char c) {
		try {
			return String.valueOf(c).getBytes("UTF-8").length > 1;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 验证字符串内容是否包含下列非法字符<br>
	 * `~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆
	 *
	 * @param content 字符串内容
	 * @return 't'代表不包含非法字符，otherwise代表包含非法字符。
	 */
	public static char validateLegalString(String content) {
		String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
		char isLegalChar = 't';
		L1: for (int i = 0; i < content.length(); i++) {
			for (int j = 0; j < illegal.length(); j++) {
				if (content.charAt(i) == illegal.charAt(j)) {
					isLegalChar = content.charAt(i);
					break L1;
				}
			}
		}
		return isLegalChar;
	}

	/**
	 * 验证是否是汉字或者0-9、a-z、A-Z
	 *
	 * @param c 被验证的char
	 * @return true代表符合条件
	 */
	public static boolean isRightChar(char c) {
		return isChinese(c) || isWord(c);
	}

	/**
	 * 校验某个字符是否是a-z、A-Z、_、0-9
	 *
	 * @param c 被校验的字符
	 * @return true代表符合条件
	 */
	public static boolean isWord(char c) {
		String regEx = "[\\w]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher("" + c);
		return m.matches();
	}

	/**
	 * 判定输入的是否是汉字
	 *
	 * @param c 被校验的字符
	 * @return true代表是汉字
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 校验String是否全是中文
	 *
	 * @param name 被校验的字符串
	 * @return true代表全是汉字
	 */
	public static boolean checkNameChese(String name) {
		boolean res = true;
		char[] cTemp = name.toCharArray();
		for (int i = 0; i < name.length(); i++) {
			if (!isChinese(cTemp[i])) {
				res = false;
				break;
			}
		}
		return res;
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 * @return
	 */
	public static String md5Crypt(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexString.toString();
	}

	/**
	 * 将两个字符串数组合并成一个字符串数组
	 * 
	 * @param arr1
	 * @param arr2
	 * @return
	 */
	public static String[] combineArr(String[] arr1, String[] arr2) {
		String[] newArr = new String[arr1.length + arr2.length];
		for (int x = 0; x < arr1.length; x++) {
			newArr[x] = arr1[x];
		}
		for (int y = 0; y < arr2.length; y++) {
			newArr[arr1.length + y] = arr2[y];
		}
		return newArr;
	}

	/**
	 * 判断是否为整数
	 * 
	 * @param str 传入的字符串
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 把Object 转化成指定泛型类型对象
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static <T> T initObject(Object object, Class<T> clazz) {
		return (T) clazz.cast(object);
	}

	public static Boolean keywords(String text, List<String> keywords) {
		Boolean flag = false;
		for (String str : keywords) {
			if (str.contains("&") || str.contains(" ")) {
				String[] words = str.split("&");
				if (words.length < 1) {
					words = str.split(" ");
				}
				if (contain(text, words[0]) && contain(text, words[1])) {
					flag = true;
					break;
				}
			} else {
				if (contain(text, str)) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	}

	public static Boolean contain(String text, String keyword) {
		Boolean flag = false;
		if (StringUtils.isNoneBlank(text) && text.contains(keyword)) {
			flag = true;
		}
		return flag;
	}

	/*
	 * list去重
	 */
	public static List<String> removeDuplicate(List<String> list) {
		HashSet<String> h = new HashSet<String>(list);
		list.clear();
		list.addAll(h);
		return list;
	}

	/**
	 * 获得唯一ID
	 * 
	 * @return
	 */
	public static String getSingleId() {
		String formatType = "yyyyMMddHHmmssSSS";
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(formatType);
		String singleId = format.format(date);
		int ran = getRandomInt(100, 999);
		singleId = singleId + "-" + ran;
		return singleId;
	}

	// 特殊字符替换成_
	public static String StringFilter(String str) {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
}
